import { ActionReducerMapBuilder, AsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { createAsyncThunk } from "@reduxjs/toolkit";
import { fetchGraphCodeAPI, fetchMobileCodeAPI, loginAPI } from "@/api/loginAPI";
import { GraphCode, LoginData, LoginParams, MobileCode } from "@/type/LoginType";
import { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";


type InitialState = {
   graphCode: GraphCode;
   loginData: LoginData;
}

const initialState: InitialState = {
   graphCode: {} as GraphCode,
   loginData: JSON.parse(localStorage.getItem("loginInfo") as string) || {} as LoginData,
};

/**
 * 获取图形验证码的AsyncThunk函数
 * */
export const fetchGraphCodeThunk: AsyncThunk<GraphCode, void, AsyncThunkConfig> = createAsyncThunk("", async (_, { rejectWithValue }) => {
   try {
      const { data } = await fetchGraphCodeAPI();
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * 获取手机验证码的AsyncThunk函数
 * */
export const fetchMobileCodeThunk: AsyncThunk<[], MobileCode, AsyncThunkConfig> = createAsyncThunk("fetchMobileCode", async (mobileCode, { rejectWithValue }) => {
   try {
      const { data } = await fetchMobileCodeAPI(mobileCode);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 登录的AsyncThunk函数
 * */
export const loginThunk: AsyncThunk<LoginData, LoginParams, AsyncThunkConfig> = createAsyncThunk("loginThunk", async (loginParams, { rejectWithValue }) => {
   try {
      const { data } = await loginAPI(loginParams);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const loginStore = createSlice({
   name: "homeStore",
   initialState,
   reducers: {
      logout(state: InitialState) {
         state.loginData = {} as LoginData;
         localStorage.removeItem("loginInfo");
      },
   },
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchGraphCodeThunk.fulfilled, (state: InitialState, action: PayloadAction<GraphCode>) => {
         state.graphCode = action.payload;
      });
      builder.addCase(loginThunk.fulfilled, (state: InitialState, action: PayloadAction<LoginData>) => {
         state.loginData = action.payload;
         localStorage.setItem("loginInfo", JSON.stringify(action.payload));
      });
   },

});

export const { logout } = loginStore.actions;

export default loginStore.reducer;
